package com.fangcun.service.api.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fangcun.bean.api.goods.response.GoodsDetailResponse;
import com.fangcun.bean.api.order.request.GoodsCreateOrderRequest;
import com.fangcun.bean.api.order.request.OrderApplyRefundRequest;
import com.fangcun.bean.api.order.request.OrderDetailRequest;
import com.fangcun.bean.api.order.request.OrderListRequest;
import com.fangcun.bean.api.order.request.OrderRevokeRefundRequest;
import com.fangcun.bean.api.order.request.ShopCartCreateOrderRequest;
import com.fangcun.bean.api.order.response.OrderCreateResponse;
import com.fangcun.bean.api.order.response.OrderDetailResponse;
import com.fangcun.bean.api.order.response.OrderGoodsDetailResponse;
import com.fangcun.bean.api.order.response.OrderGoodsListResponse;
import com.fangcun.bean.api.order.response.OrderListResponse;
import com.fangcun.bean.api.order.response.OrderStatusNumberResponse;
import com.fangcun.bean.api.order.response.ShopCartSearchResponse;
import com.fangcun.bean.sys.PageBean;
import com.fangcun.bean.sys.pay.PayResultMsg;
import com.fangcun.common.async.AsyncMethod;
import com.fangcun.common.canstant.ErrCode;
import com.fangcun.common.canstant.PublicConstant;
import com.fangcun.common.enums.OrderStatusEnum;
import com.fangcun.common.enums.PayCodeEnum;
import com.fangcun.common.exception.ProAffairException;
import com.fangcun.common.exception.ProRunTimeException;
import com.fangcun.common.exception.ProValiDataException;
import com.fangcun.common.util.BeanMapper;
import com.fangcun.common.util.PublicMethod;
import com.fangcun.common.util.base.BaseService;
import com.fangcun.common.util.date.DateUtils;
import com.fangcun.common.util.wxpay.WXPayUtils;
import com.fangcun.entity.GoodsPrice;
import com.fangcun.entity.Order;
import com.fangcun.entity.OrderAddress;
import com.fangcun.entity.OrderDetail;
import com.fangcun.entity.OrderGoods;
import com.fangcun.entity.OrderRefund;
import com.fangcun.entity.SysPayment;
import com.fangcun.entity.UserReceivingAddress;
import com.fangcun.mapper.GoodsMapper;
import com.fangcun.mapper.GoodsPriceMapper;
import com.fangcun.mapper.OrderAddressMapper;
import com.fangcun.mapper.OrderDetailMapper;
import com.fangcun.mapper.OrderGoodsMapper;
import com.fangcun.mapper.OrderMapper;
import com.fangcun.mapper.OrderRefundMapper;
import com.fangcun.mapper.OrderShoppingcartMapper;
import com.fangcun.mapper.SysPaymentMapper;
import com.fangcun.mapper.UserLoginMapper;
import com.fangcun.mapper.UserReceivingAddressMapper;
import com.fangcun.service.api.OrderApiService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @作者： 陳曉鬆 @时间： 2020年7月16日 - 上午11:43:33 @description：->
 */
@Service("orderApiService")
public class OrderApiServiceImpl extends BaseService implements OrderApiService {

	private static Logger LOG = LoggerFactory.getLogger(OrderApiServiceImpl.class);

	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private GoodsPriceMapper goodsPriceMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private UserReceivingAddressMapper userReceivingAddressMapper;
	@Autowired
	private OrderAddressMapper orderAddressMapper;
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private OrderGoodsMapper orderGoodsMapper;
	@Autowired
	private OrderRefundMapper orderRefundMapper;
	@Autowired
	private SysPaymentMapper paymentMapper;
	@Autowired
	private UserLoginMapper userLoginMapper;
	@Autowired
	private OrderShoppingcartMapper orderShoppingcartMapper;
	@Autowired
	private AsyncMethod asyncMethod;

	@Override
	@Transactional
	public OrderCreateResponse shopCartCreateOrder(ShopCartCreateOrderRequest request) throws ProAffairException {
		synchronized (request.getTeahouseId()) {// 相同分销商同一时间只能有一个人下单
			List<ShopCartSearchResponse> cartList = orderShoppingcartMapper.selectForApi(null, null, request.getCartIds());
			if (cartList == null || cartList.size() == 0) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}
			// 判读上下架 剩余量是否能够下单
			/** 商品总金额 **/
			BigDecimal goodsTotalPrice = new BigDecimal("0");
			/** 商品总优惠金额 **/
			BigDecimal goodsTotalVoucherPrice = new BigDecimal("0");
			/** 运费 **/
			BigDecimal logisticsPrice = new BigDecimal("0");
			for (ShopCartSearchResponse cart : cartList) {
					if (request.getTeahouseId() != cart.getTeahouseId()) {
						throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "茶楼与订单创建信息不匹配");
					}
				if (cart.getStatus() != PublicConstant.GOODS_STATUS_1) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + cart.getTitle() + "】已经下架！无法下单");
				}
				if (cart.getBanlanceNumber() < cart.getNumber()) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + cart.getTitle() + "】数量不足！无法下单，剩余数量：" + cart.getBanlanceNumber());
				}
				// 运费取最大值
				if (cart.getLogisticsPrice().doubleValue() > logisticsPrice.doubleValue()) {
					logisticsPrice = cart.getLogisticsPrice();
				}
				BigDecimal price = cart.getPrice().multiply(new BigDecimal(cart.getNumber().toString()));
				BigDecimal voucherPrice = cart.getVoucherPrice().multiply(new BigDecimal(cart.getNumber().toString()));
				goodsTotalPrice = goodsTotalPrice.add(price).setScale(2, BigDecimal.ROUND_HALF_UP);
				goodsTotalVoucherPrice = goodsTotalVoucherPrice.add(voucherPrice).setScale(2, BigDecimal.ROUND_HALF_UP);

				// 减掉剩余数量 增加销售量
				GoodsPrice updateGoods = new GoodsPrice();
				updateGoods.setId(cart.getResId());
				updateGoods.setBanlanceNumber(cart.getBanlanceNumber() - cart.getNumber());
				if (goodsPriceMapper.updateByPrimaryKeySelective(updateGoods) == 0) {
					throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "更改商品剩余数量出错");
				}
			}
			UserReceivingAddress address = userReceivingAddressMapper.selectByPrimaryKey(request.getAddressId());
			if (address == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}
			// 生成主订单
			Date nowDate = new Date();
			Order main = new Order();
			main.setOrderNumber(PublicMethod.getOrderNumber(PublicConstant.ORDER_TYPE_1, null));
			main.setUserId(request.getUserId());
			main.setTeahouseId(request.getTeahouseId());
			main.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus());
			main.setCreateTime(nowDate);
			main.setInvalidTime(DateUtils.getAddorSubtractTimes(nowDate, 0, PublicConstant.ORDER_INVALID_TIME, 0, 0, 0, 0));
			main.setActualPrice(goodsTotalPrice.add(logisticsPrice));
			main.setVoucherPrice(goodsTotalVoucherPrice);
			main.setLogisticsPrice(logisticsPrice);
			main.setTotalPrice(main.getActualPrice().add(main.getVoucherPrice()));
			main.setSource(request.getSource());
			main.setRemark(request.getRemark());
			main.setIp(PublicMethod.getIp(PublicMethod.getRequest()));
			if (orderMapper.insertSelective(main) == 0 || main.getId() == null) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "主订单," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 地址
			OrderAddress orderAddress = BeanMapper.map(address, OrderAddress.class);
			orderAddress.setMainOrderId(main.getId());
			orderAddress.setId(null);
			if (orderAddressMapper.insertSelective(orderAddress) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "记录地址失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 订单详情
			for (ShopCartSearchResponse cart : cartList) {
				OrderDetail detail = new OrderDetail();
				detail.setMainOrderId(main.getId());
				detail.setNumber(cart.getNumber());
				detail.setOriginalPriceId(cart.getResId());
				if (orderDetailMapper.insertSelective(detail) == 0 || detail.getId() == null) {
					throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "详情," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
				}
				// 商品
				OrderGoods orderGoods = BeanMapper.map(cart, OrderGoods.class);
				orderGoods.setDetailId(detail.getId());
				orderGoods.setCategoryId(cart.getParentCategoryId());
				orderGoods.setId(null);
				if (orderGoodsMapper.insertSelective(orderGoods) == 0) {
					throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "商品创建失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
				}
			}
			// 删除购物车
			if (orderShoppingcartMapper.deleteByIds(request.getCartIds()) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "清除购物车失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 返回
			OrderCreateResponse response = new OrderCreateResponse();
			response.setOrderNumber(main.getOrderNumber());
			response.setOrderStatus(main.getOrderStatus());
			response.setCreateTime(main.getCreateTime());
			response.setInvalidTime(main.getInvalidTime());
			response.setActualPrice(main.getActualPrice());
			return response;
		}
	}

	@Override
	@Transactional
	public OrderCreateResponse createOrderByGoods(GoodsCreateOrderRequest request) throws ProAffairException {
		// 返回实体
		synchronized (request.getPriceId()) {// 同一个价格id 只能一人次下单
			GoodsDetailResponse detailResponse = goodsMapper.detailForApi(request.getPriceId(), request.getUserId());
			if (detailResponse == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}
			// 判读上下架 剩余量是否能够下单
			/** 商品总金额 **/
			BigDecimal goodsTotalPrice = new BigDecimal("0");
			/** 商品总优惠金额 **/
			BigDecimal goodsTotalVoucherPrice = new BigDecimal("0");
			/** 运费 **/
			BigDecimal logisticsPrice = detailResponse.getLogisticsPrice();
			if (request.getTeahouseId() != detailResponse.getTeahouseId()) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "分销商与订单创建信息不匹配");
			}
			if (detailResponse.getStatus() != PublicConstant.GOODS_STATUS_1) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + detailResponse.getTitle() + "】已经下架！无法下单");
			}
			if (detailResponse.getBanlanceNumber() < request.getNumber()) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + detailResponse.getTitle()+ "】数量不足！无法下单，剩余数量：" + detailResponse.getBanlanceNumber());
			}
			BigDecimal price = detailResponse.getPrice().multiply(new BigDecimal(request.getNumber().toString()));
			BigDecimal voucherPrice = detailResponse.getVoucherPrice().multiply(new BigDecimal(request.getNumber().toString()));
			goodsTotalPrice = goodsTotalPrice.add(price).setScale(2, BigDecimal.ROUND_HALF_UP);
			goodsTotalVoucherPrice = goodsTotalVoucherPrice.add(voucherPrice).setScale(2, BigDecimal.ROUND_HALF_UP);

			// 减掉剩余数量 增加销售量
			GoodsPrice updateGoods = new GoodsPrice();
			updateGoods.setId(detailResponse.getPriceId());
			updateGoods.setBanlanceNumber(detailResponse.getBanlanceNumber() - request.getNumber());
			if (goodsPriceMapper.updateByPrimaryKeySelective(updateGoods) == 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "更改商品剩余数量出错");
			}
			UserReceivingAddress address = userReceivingAddressMapper.selectByPrimaryKey(request.getAddressId());
			if (address == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}
			// 生成主订单
			Date nowDate = new Date();
			Order main = new Order();
			main.setOrderNumber(PublicMethod.getOrderNumber(PublicConstant.ORDER_TYPE_1, null));
			main.setUserId(request.getUserId());
			main.setTeahouseId(request.getTeahouseId());
			main.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus());
			main.setCreateTime(nowDate);
			main.setInvalidTime(DateUtils.getAddorSubtractTimes(nowDate, 0, PublicConstant.ORDER_INVALID_TIME, 0, 0, 0, 0));
			main.setActualPrice(goodsTotalPrice.add(logisticsPrice));
			main.setVoucherPrice(goodsTotalVoucherPrice);
			main.setLogisticsPrice(logisticsPrice);
			main.setTotalPrice(main.getActualPrice().add(main.getVoucherPrice()));
			main.setSource(request.getSource());
			main.setRemark(request.getRemark());
			main.setIp(PublicMethod.getIp(PublicMethod.getRequest()));
			if (orderMapper.insertSelective(main) == 0 || main.getId() == null) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "主订单," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 地址
			OrderAddress orderAddress = BeanMapper.map(address, OrderAddress.class);
			orderAddress.setMainOrderId(main.getId());
			orderAddress.setId(null);
			if (orderAddressMapper.insertSelective(orderAddress) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "记录地址失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 订单详情
			OrderDetail detail = new OrderDetail();
			detail.setMainOrderId(main.getId());
			detail.setNumber(request.getNumber());
			detail.setOriginalPriceId(detailResponse.getPriceId());
			if (orderDetailMapper.insertSelective(detail) == 0 || detail.getId() == null) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "详情," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 商品
			OrderGoods orderGoods = BeanMapper.map(detailResponse, OrderGoods.class);
			orderGoods.setDetailId(detail.getId());
			orderGoods.setCategoryId(detail.getCategoryId());
			orderGoods.setId(null);
			if (orderGoodsMapper.insertSelective(orderGoods) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "商品创建失败," + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}
			// 返回
			OrderCreateResponse response = new OrderCreateResponse();
			response.setOrderNumber(main.getOrderNumber());
			response.setOrderStatus(main.getOrderStatus());
			response.setCreateTime(main.getCreateTime());
			response.setInvalidTime(main.getInvalidTime());
			response.setActualPrice(main.getActualPrice());
			return response;
		}
	}

	@Override
	@Transactional
	public OrderCreateResponse createOrderByGoodsForLQH(GoodsCreateOrderRequest request) throws ProAffairException {
		// 返回实体
		synchronized (request.getPriceId()) {// 同一个价格id 只能一人次下单
			GoodsDetailResponse detailResponse = goodsMapper.detailForApi(request.getPriceId(), request.getUserId());
			if (detailResponse == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
			}
			UserReceivingAddress address = userReceivingAddressMapper.selectByPrimaryKey(request.getAddressId());
			if (address == null) {
				throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "地址信息" + ErrCode.NO_DATA.getReturnMsg());
			}
			if (request.getNumber() > detailResponse.getBanlanceNumber()) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "剩余数量不足以下单");
			}
			if (detailResponse.getLimitPerOrder() != 0 && request.getNumber() > detailResponse.getLimitPerOrder()) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "超出购买数量限制");
			}
			// 修改产品价格剩余数量
			if (goodsPriceMapper.updateBlanceNumberById(request.getPriceId(), request.getNumber() * -1) == 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "修改商品剩余数量出错");
			}
			// 计算价格
			BigDecimal actualPrice = detailResponse.getPrice().multiply(BigDecimal.valueOf(request.getNumber()));

			// 加上快递费用
			actualPrice = actualPrice.add(detailResponse.getLogisticsPrice());
			BigDecimal voucherPrice = detailResponse.getVoucherPrice().multiply(BigDecimal.valueOf(request.getNumber()));

			// 优惠价格计算
			BigDecimal acVoucherPrice = BigDecimal.valueOf(0);
			if (detailResponse.getPrice().doubleValue() == 68 && request.getNumber() >= 2) {
				acVoucherPrice = BigDecimal.valueOf(request.getNumber() * -8);
			}
			if (detailResponse.getPrice().doubleValue() == 88 && request.getNumber() >= 2) {
				acVoucherPrice = BigDecimal.valueOf(request.getNumber() * -8);
			}
			if (acVoucherPrice.doubleValue() != 0) {
				actualPrice = actualPrice.add(acVoucherPrice);
				voucherPrice = voucherPrice.add(acVoucherPrice.multiply(BigDecimal.valueOf(-1)));
			}

			// 最后价格
			actualPrice = actualPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
			voucherPrice = voucherPrice.setScale(2, BigDecimal.ROUND_HALF_UP);

			// 返回参数实体
			OrderCreateResponse response = new OrderCreateResponse();

			// 主订单
			Order order = new Order();
			order.setOrderNumber(PublicMethod.getOrderNumber(PublicConstant.ORDER_TYPE_1, null));
			order.setUserId(request.getUserId());
			order.setTeahouseId(detailResponse.getTeahouseId());
			order.setCreateTime(new Date());
			order.setInvalidTime(DateUtils.getAddorSubtractTimes(order.getCreateTime(), 0, PublicConstant.ORDER_INVALID_TIME, 0, 0, 0, 0));
			if (request.getIsOnlinePayment() == 2) {
				order.setInvalidTime(DateUtils.getAddorSubtractTimes(order.getCreateTime(), 0, 0, 0, 1, 0, 0));
			}
			order.setIsOnlinePayment(request.getIsOnlinePayment());
			order.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus());
			order.setTotalPrice(actualPrice.add(voucherPrice));
			order.setVoucherPrice(voucherPrice);
			order.setLogisticsPrice(detailResponse.getLogisticsPrice());
			order.setActualPrice(actualPrice);
			order.setSource(request.getSource());
			order.setIp(PublicMethod.getIp(PublicMethod.getRequest()));
			order.setRemark(request.getRemark());
			if (orderMapper.insertSelective(order) == 0 || order.getId() == null) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}

			// 地址
			OrderAddress orderAddress = BeanMapper.map(address, OrderAddress.class);
			orderAddress.setId(null);
			orderAddress.setMainOrderId(order.getId());
			orderAddress.setType(request.getAddressType());
			if (orderAddressMapper.insertSelective(orderAddress) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "地址：" + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}

			// 详情
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setMainOrderId(order.getId());
			orderDetail.setNumber(request.getNumber());
			orderDetail.setOriginalPriceId(request.getPriceId());
			if (orderDetailMapper.insertSelective(orderDetail) == 0 || orderDetail.getId() == null) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "详情：" + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}

			// 商品
			OrderGoods orderGoods = BeanMapper.map(detailResponse, OrderGoods.class);
			orderGoods.setId(null);
			orderGoods.setDetailId(order.getId());
			if (orderGoodsMapper.insertSelective(orderGoods) == 0) {
				throw new ProRunTimeException(ErrCode.ORDER_INSERT_FAIL.getReturnCode(), "商品：" + ErrCode.ORDER_INSERT_FAIL.getReturnMsg());
			}

			response.setActualPrice(actualPrice);
			response.setCreateTime(order.getCreateTime());
			response.setInvalidTime(order.getInvalidTime());
			response.setOrderNumber(order.getOrderNumber());
			response.setOrderStatus(order.getOrderStatus());
			response.setIsPay(request.getIsOnlinePayment() == 1 ? OrderCreateResponse.IS_PAY_1 : OrderCreateResponse.IS_PAY_2);
			return response;
		}
	}

	@Override
	public PageInfo<OrderListResponse> list(PageBean<OrderListRequest> request) throws ProAffairException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<OrderListResponse> list = orderMapper.listForApi(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}

	@Override
	public OrderDetailResponse detail(OrderDetailRequest request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getOrderNumber())) {
			throw new ProAffairException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		OrderDetailResponse response = orderMapper.detailForApi(request);
		if (response == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return response;
	}

	@Override
	public void invalidOrderCancel() {
		OrderListRequest request = new OrderListRequest();
		List<Integer> status = new ArrayList<Integer>();
		status.add(OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus());
		request.setStatus(status);
		request.setQueryInvalidOrder(true);
		List<OrderListResponse> invalidOrderList = orderMapper.listForApi(request);
		if (invalidOrderList == null || invalidOrderList.size() == 0) {
			return;
		}
		for (OrderListResponse o : invalidOrderList) {
			try {
				// 设置为取消订单
				Order orderMain = new Order();
				orderMain.setId(o.getId());
				orderMain.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_5.getStatus());
				if (orderMapper.updateByPrimaryKeySelective(orderMain) == 0) {
					throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "修改订单状态失败");
				}

				// 返还库存
				for (OrderGoodsListResponse d : o.getGoodsList()) {
					goodsPriceMapper.updateBlanceNumberById(d.getOriginalPriceId(), d.getNumber());
				}

			} catch (Exception e) {
				LOG.error("-订单-取消订单->{},异常:{}", o.getOrderNumber(), PublicMethod.printErrorTrace(e));
			}
		}
	}

	@Override
	@Transactional
	public void confirmReceivingGoods(Long orderId, Long userId) throws ProAffairException {
		Order orderMain = orderMapper.selectByPrimaryKey(orderId);
		if (orderMain == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (userId.longValue() != orderMain.getUserId().longValue()) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_3.getStatus() != orderMain.getOrderStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(), "该订单目前不是已发货状态,无法确认收货");
		}
		orderMain.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_4.getStatus());
		orderMain.setReceivingTime(new Date());
		if (orderMapper.updateByPrimaryKeySelective(orderMain) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "确认收货发生错误,请重试");
		}
	}

	@Override
	@Transactional
	public void updateOrderByIsdelete(List<Long> orderIds) throws ProAffairException {
		for (Long id : orderIds) {
			Order orderMain = new Order();
			orderMain.setId(id);
			orderMain.setIsDelete(0);
			if (orderMapper.updateByPrimaryKeySelective(orderMain) == 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "删除订单发生错误,请重试");
			}
		}
	}

	@Override
	@Transactional
	public List<OrderStatusNumberResponse> getOrderStatusNumber(Long userId) throws ProAffairException {
		List<OrderStatusNumberResponse> list = orderMapper.getOrderStatusNumberList(userId);
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return list;
	}

	@Override
	@Transactional
	public OrderDetailResponse applyRefund(OrderApplyRefundRequest request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getOrderNumber()) || request.getRefundPrice() == null) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		OrderDetailRequest orderRequest = new OrderDetailRequest();
		orderRequest.setOrderNumber(request.getOrderNumber());
		orderRequest.setUserId(request.getUserId());
		OrderDetailResponse detail = orderMapper.detailForApi(orderRequest);
		if (detail == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_2.getStatus() != detail.getOrderStatus() && OrderStatusEnum.MAIN_ORDER_STATUS_3.getStatus() != detail.getOrderStatus()
				&& OrderStatusEnum.MAIN_ORDER_STATUS_4.getStatus() != detail.getOrderStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_NO_REFUND.getReturnCode(), ErrCode.ORDER_STATUS_NO_REFUND.getReturnMsg());
		}
		if (detail.getActualPrice().doubleValue() < request.getRefundPrice().doubleValue()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_NO_REFUND.getReturnCode(), "退款金额大于购买价格");
		}
		if (detail.getRefund() == null) {// 第一次申请
			// 生成退款单
			OrderRefund refund = new OrderRefund();
			refund.setMainOrderId(detail.getId());
			refund.setRefundPrice(request.getRefundPrice());
			refund.setRefundNumber(PublicMethod.getOrderNumber(PublicConstant.ORDER_TYPE_2, detail.getId()));
			refund.setRefundStatus(OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus());
			refund.setRemark(request.getRemark());
			refund.setRefundImage(request.getRefundImage());
			refund.setRefundReason(request.getRefundReason());
			if (orderRefundMapper.insertSelective(refund) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "退货退款申请失败");
			}
			// 修改主订单子状态
			Order updateOrder = new Order();
			updateOrder.setId(detail.getId());
			updateOrder.setOrderSubStatus(OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus());
			if (orderMapper.updateByPrimaryKeySelective(updateOrder) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "退货退款申请失败");
			}
		} else {// 重新申请
			OrderRefund refund = detail.getRefund();
			if (OrderStatusEnum.REFUND_ORDER_STATUS_10.getStatus() != refund.getRefundStatus()) {
				throw new ProRunTimeException(ErrCode.ORDER_STATUS_NO_REFUND.getReturnCode(), "您已经申请过退货退款");
			}
			refund.setRefundPrice(request.getRefundPrice());
			refund.setRefundStatus(OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus());
			refund.setFailRemark("");
			refund.setRefundImage(request.getRefundImage());
			refund.setRemark(request.getRemark());
			refund.setRefundReason(request.getRefundReason());
			// 重新申请先删除原来的，然后在提交，把最新提交的放到最后面审核
			if (orderRefundMapper.deleteByPrimaryKey(refund.getId()) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "删除旧的退货退款失败");
			}
			refund.setId(null);
			refund.setUpdateTime(new Date());
			if (orderRefundMapper.insertSelective(refund) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "退货退款再次申请失败");
			}
			// 修改主订单子状态
			Order updateOrder = new Order();
			updateOrder.setId(detail.getId());
			updateOrder.setOrderSubStatus(OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus());
			if (orderMapper.updateByPrimaryKeySelective(updateOrder) <= 0) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "退货退款申请失败");
			}
		}
		return detail(orderRequest);
	}

	@Override
	@Transactional
	public void revokeRefund(OrderRevokeRefundRequest request) throws ProAffairException {
		if (StringUtils.isEmpty(request.getOrderNumber())) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		OrderDetailRequest orderRequest = new OrderDetailRequest();
		orderRequest.setUserId(request.getUserId());
		orderRequest.setOrderNumber(request.getOrderNumber());
		OrderDetailResponse detail = orderMapper.detailForApi(orderRequest);
		if (detail == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (request.getUserId().longValue() != detail.getUserId().longValue()) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		if (detail.getRefund() == null) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REFUND_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REFUND_REQUEST.getReturnMsg());
		}
		OrderRefund refund = detail.getRefund();
		if (OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus() != refund.getRefundStatus() && OrderStatusEnum.REFUND_ORDER_STATUS_9.getStatus() != refund.getRefundStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_REFUND_DEAL.getReturnCode(), ErrCode.ORDER_REFUND_DEAL.getReturnMsg());
		}
		if (orderRefundMapper.deleteByPrimaryKey(refund.getId()) <= 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "撤销退货申请失败,请稍后重试");
		}
	}

	@Override
	@Transactional
	public Object pay(String orderNumber, Long userId, Integer payType, Integer source) throws ProAffairException {
		OrderDetailRequest request = new OrderDetailRequest();
		request.setOrderNumber(orderNumber);
		request.setUserId(userId);
		OrderDetailResponse response = orderMapper.detailForApi(request);
		if (response == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (response.getUserId() != userId) {
			throw new ProRunTimeException(ErrCode.ORDER_NO_REQUEST.getReturnCode(), ErrCode.ORDER_NO_REQUEST.getReturnMsg());
		}
		if (response.getOrderStatus() != OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(), ErrCode.ORDER_STATUS_UPDATE.getReturnMsg() + ":无法完成支付");
		}
		if (response.getInvalidTime().getTime() <= System.currentTimeMillis()) {
			throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(), "该订单已经过期，不能继续支付");
		}
		for (OrderGoodsDetailResponse order : response.getGoodsDetailList()) {
			GoodsDetailResponse goods = goodsMapper.detailForApi(order.getOriginalPriceId(), userId);
			if (goods == null) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品已经下架！无法支付");
			}
			if (goods.getStatus() != PublicConstant.GOODS_STATUS_1) {
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "商品【" + goods.getTitle() + "】已经下架！无法支付");
			}
		}
		if (payType == null) {
			payType = 2;
		}
		SysPayment payment = paymentMapper.selectByPayTypeAndSource(payType, source);
		if (payment == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "支付信息不存在");
		}
		// 小程序支付
		if (PayCodeEnum.WECHAT.getType() == payment.getPayType() && PayCodeEnum.SOURCE_1.getType() == source) {
			return WXPayUtils.xcxPay(response, payment, userLoginMapper.selectByUserIdAndAppid(response.getUserId(), payment.getPayAppid()));
		}
		// H5支付
		if (PayCodeEnum.WECHAT.getType() == payment.getPayType() && PayCodeEnum.SOURCE_2.getType() == source) {
			return WXPayUtils.h5Pay(response, payment);
		}
		// 微信公众号支付
		if (PayCodeEnum.WECHAT.getType() == payment.getPayType() && PayCodeEnum.SOURCE_3.getType() == source) {
			return WXPayUtils.publicNumberPay(response, payment, userLoginMapper.selectByUserIdAndAppid(response.getUserId(), payment.getPayAppid()));
		}
		// 微信APP支付
		if (PayCodeEnum.WECHAT.getType() == payment.getPayType() && (PayCodeEnum.SOURCE_4.getType() == source || PayCodeEnum.SOURCE_5.getType() == source)) {
			return WXPayUtils.appPay(response, payment);
		}
		throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "没有该支付信息");
	}

	@Override
	@Transactional
	public void dealPayNotify(PayResultMsg payResultMsg) throws ProAffairException {
		// 根据支付订单号查询订单
		OrderDetailRequest request = new OrderDetailRequest();
		request.setOrderNumber(payResultMsg.getOrderNumber());
		OrderDetailResponse order = orderMapper.detailForApi(request);
		if (order == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		// 微信设置Unionid
		if (PayCodeEnum.WECHAT.getType().intValue() == payResultMsg.getPayType().intValue()) {
			asyncMethod.settingUnionid(order.getUserId(), payResultMsg.getAppid(), payResultMsg.getOpenid(), payResultMsg.getBillNo());
		}
		if (payResultMsg.getPayPrice().doubleValue() != order.getActualPrice().doubleValue()) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "支付金额不对等,需人工排查订单");
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_1.getStatus().intValue() != order.getOrderStatus().intValue()) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "该订单已经处理过了：" + order.getOrderStatus());
		}
		order.setPayType(payResultMsg.getPayType());
		order.setPayBillNumber(payResultMsg.getBillNo());
		order.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_2.getStatus());
		order.setPayTime(payResultMsg.getPayTime());
		if (orderMapper.updateByPrimaryKeySelective(order) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "修改订单失败,需人工排查订单");
		}
	}

}
